<template>
    <div class="profile-container">
        <el-row :gutter="20">
            <el-col :span="7">
                <el-card class="left-card">
                    <div class="title">个人信息</div>
                    <div class="info-content">
                        <el-upload class="avatar-uploader" 
                            :action="uploadUrl"
                            :headers="uploadHeaders"
                            :show-file-list="false" :before-upload="beforeAvatarUpload"
                            :on-success="handleAvatarSuccess">
                            <el-avatar v-if="userInfo.avatar" :src="userInfo.avatar" :size="120" />
                            <el-avatar v-else :size="120">
                                {{ userInfo.nickname?.charAt(0)?.toUpperCase() }}
                            </el-avatar>
                        </el-upload>
                        <div class="info-item">
                            <i class="el-icon-user"></i>
                            <span class="label">用户名称</span>
                            <span class="value">{{ userInfo.nickname }}</span>
                        </div>
                        <div class="info-item">
                            <i class="el-icon-mobile"></i>
                            <span class="label">手机号码</span>
                            <span class="value">{{ userInfo.phone }}</span>
                        </div>
                        <div class="info-item">
                            <i class="el-icon-message"></i>
                            <span class="label">用户邮箱</span>
                            <span class="value">{{ userInfo.email }}</span>
                        </div>
                        <div class="info-item">
                            <i class="el-icon-user"></i>
                            <span class="label">所属角色</span>
                            <span class="value">{{ userInfo.role }}</span>
                        </div>
                        <div class="info-item">
                            <i class="el-icon-date"></i>
                            <span class="label">创建日期</span>
                            <span class="value">{{ userInfo.createdTime }}</span>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="16">
                <el-card>
                    <el-tabs v-model="activeTab">
                        <el-tab-pane label="基本资料" name="basic">
                            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                                <el-form-item label="用户昵称" prop="nickname">
                                    <el-input v-model="form.nickname" placeholder="请输入用户昵称" />
                                </el-form-item>
                                <el-form-item label="手机号码" prop="phone">
                                    <el-input v-model="form.phone" placeholder="请输入手机号码" />
                                </el-form-item>
                                <el-form-item label="邮箱" prop="email">
                                    <el-input v-model="form.email" placeholder="请输入邮箱" />
                                </el-form-item>
                                <el-form-item label="性别">
                                    <el-radio-group v-model="form.gender">
                                        <el-radio :label="1">男</el-radio>
                                        <el-radio :label="2">女</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="handleSubmit">保存</el-button>
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>
                        <el-tab-pane label="修改密码" name="password">
                            <el-form ref="pwdFormRef" :model="pwdForm" :rules="pwdRules" label-width="100px">
                                <el-form-item label="原密码" prop="oldPassword">
                                    <el-input v-model="pwdForm.oldPassword" type="password" placeholder="请输入原密码"
                                        show-password />
                                </el-form-item>
                                <el-form-item label="新密码" prop="newPassword">
                                    <el-input v-model="pwdForm.newPassword" type="password" placeholder="请输入新密码"
                                        show-password />
                                </el-form-item>
                                <el-form-item label="确认密码" prop="confirmPassword">
                                    <el-input v-model="pwdForm.confirmPassword" type="password" placeholder="请确认新密码"
                                        show-password />
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="handleUpdatePassword">确认修改</el-button>
                                    <el-button @click="resetPwdForm">重置</el-button>
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>
                    </el-tabs>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { useRouter } from 'vue-router'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/store/user'

const userInfo = ref({})
const formRef = ref(null)
const activeTab = ref('basic')
const pwdFormRef = ref(null)
const router = useRouter()

// 上传图片地址
const uploadUrl = baseURL + '/common/img/upload'

// 获取token
const getToken = () => {
    // return JSON.parse(localStorage.getItem('userInfo'))?.token
    return useUserStore().userInfo?.token
}

// 请求头
const uploadHeaders = {
    Authorization: getToken()
}

const form = reactive({
    nickname: '',
    email: '',
    phone: '',
    gender: null
})

const pwdForm = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})

const rules = {
    nickname: [
        { required: true, message: '请输入用户昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ]
}

// 验证新密码
const validateNewPassword = (rule, value, callback) => {
    if (value === pwdForm.oldPassword) {
        callback(new Error('新密码不能与原密码相同'))
    } else {
        callback()
    }
}

// 验证确认密码
const validateConfirmPassword = (rule, value, callback) => {
    if (value !== pwdForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
    } else {
        callback()
    }
}

// 密码表单验证规则
const pwdRules = {
    oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
        { validator: validateNewPassword, trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        { validator: validateConfirmPassword, trigger: 'blur' }
    ]
}

// 获取用户信息
const getUserInfo = async () => {
    try {
        const res = await request({
            url: '/employee/info',
            method: 'get'
        })
        userInfo.value = res.data
        Object.assign(form, res.data)
    } catch (error) {
        console.error('获取用户信息失败:', error)
    }
}

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJPG) {
        ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    }
    if (!isLt2M) {
        ElMessage.error('头像大小不能超过 2MB!')
    }
    return isJPG && isLt2M
}

// 头像上传成功
const handleAvatarSuccess = (res) => {
    userInfo.value.avatar = res.data
    form.avatar = res.data
    handleSubmit();
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        await request({
            url: '/employee/update',
            method: 'put',
            data: form
        })
        ElMessage.success('保存成功')
        getUserInfo()
    } catch (error) {
        console.error('保存失败:', error)
    }
}

// 重置密码表单
const resetPwdForm = () => {
    pwdFormRef.value?.resetFields()
}

// 修改密码
const handleUpdatePassword = async () => {
    if (!pwdFormRef.value) return

    try {
        await pwdFormRef.value.validate()
        await request({
            url: '/employee/updatePwd',
            method: 'put',
            data: {
                oldPassword: pwdForm.oldPassword,
                newPassword: pwdForm.newPassword
            }
        })

        ElMessage.success('密码修改成功，请重新登录')
        // 清除登录信息
        // localStorage.removeItem('userInfo')
        useUserStore().removeUserInfo()
        // 跳转到登录页
        router.push('/login')
    } catch (error) {
        console.error('修改密码失败:', error)
    }
}

onMounted(() => {
    getUserInfo()
})
</script>

<style scoped>
.profile-container {
    padding: 20px;
}

.left-card {
    height: 100%;
}

.title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
}

.info-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 20px;
}

.avatar-uploader {
    margin-bottom: 20px;
}

.info-item {
    width: 100%;
    display: flex;
    align-items: center;
    padding: 10px 0;
}

.info-item .label {
    color: #606266;
    margin-right: 10px;
    min-width: 80px;
}

.info-item .value {
    color: #333;
    flex: 1;
}

:deep(.el-tabs__header) {
    margin-bottom: 25px;
}

:deep(.el-form-item:last-child) {
    margin-bottom: 0;
}

:deep(.el-form-item__content) {
    max-width: 400px;
}
</style>